﻿
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Extension;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;

namespace AJWPFAdmin.Core.Crypto.SMCrypto
{
    public class SM2
    {
        public static string EncryptToBase64(string value, string base64PublicKey)
        {
            ECPublicKeyParameters publicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(base64PublicKey));

            var data = Encoding.UTF8.GetBytes(value);

            var sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
            // 初始化SM2加密引擎
            sm2Engine.Init(true, new ParametersWithRandom(publicKey, new SecureRandom()));
            // 加密数据
            var cipherText = sm2Engine.ProcessBlock(data, 0, data.Length);
            return Convert.ToBase64String(cipherText);
        }

        public static byte[] EncryptToBytes(string value, string base64PublicKey)
        {
            ECPublicKeyParameters publicKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(base64PublicKey));

            var data = Encoding.UTF8.GetBytes(value);

            var sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
            // 初始化SM2加密引擎
            sm2Engine.Init(true, new ParametersWithRandom(publicKey, new SecureRandom()));
            // 加密数据
            return sm2Engine.ProcessBlock(data, 0, data.Length);
        }

        public static string Decrypt(byte[] input, string base64PrivateKey)
        {
            var privateKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(base64PrivateKey));
            //  var curve = GMNamedCurves.GetByName("sm2p256v1");
            //  ECDomainParameters domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            //  BigInteger d = new BigInteger(1, privateKeyBytes);
            //  ECPrivateKeyParameters privateKey = new ECPrivateKeyParameters(d, domainParams);

            SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
            // 初始化SM2解密引擎
            sm2Engine.Init(false, privateKey);
            // 解密数据
            return Encoding.UTF8.GetString(sm2Engine.ProcessBlock(input, 0, input.Length));
        }
    }

}
